package com.example.plant_app.service.jobhandler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.plant_app.exception.PlantException;
import com.example.plant_app.mapper.UMembersMapper;
import com.example.plant_app.mapper.UPlanetMapper;
import com.example.plant_app.mapper.UUserInfoMapper;
import com.example.plant_app.model.UMembers;
import com.example.plant_app.model.UPlanet;
import com.example.plant_app.model.UUserInfo;
import com.example.plant_app.utils.MailUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Classname CheckTime
 * @Description TODO
 * @Date 2023/6/8 13:13
 * @Created by Zh_Cn
 */
@Component
@Slf4j
public class CheckTimeTask {
    @Autowired
    UMembersMapper uMembersMapper;
    @Autowired
    UUserInfoMapper uUserInfoMapper;
    @Autowired
    UPlanetMapper uPlanetMapper;
    @XxlJob("check")
    public void checkTime(){
        //查找members表里面过期的数据
        List<UMembers> uMembers = uMembersMapper.selectList(new LambdaQueryWrapper<UMembers>()
                .le(UMembers::getEndTime, LocalDateTime.now()));
        for (UMembers uMembers1:uMembers){
            UUserInfo uUserInfo = uUserInfoMapper.selectOne
                    (new LambdaQueryWrapper<UUserInfo>().eq(UUserInfo::getId, uMembers1.getUserid()));
            UPlanet uPlanet = uPlanetMapper.selectOne
                    (new LambdaQueryWrapper<UPlanet>().eq(UPlanet::getId, uMembers1.getPlantid()));
            if (uUserInfo!=null&&uPlanet!=null){
                synchronized (this){
                    String text = "您好,您所订阅的的星球("+uPlanet.getName()+")已经过期,欢迎您再次开通!";
                    String title = "知识星球已经到期";
                    boolean b = MailUtils.sendMail(uUserInfo.getEmail(),
                            text, title);
                    if (!b){
                        PlantException.cast("发送邮箱失败");
                    }
                }
            }
            uMembersMapper.deleteById(uMembers1.getId());
        }
    }
}
